package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

//客户端
public class Client1 {
    private Socket socket;

    public Client1(){
        try {
            System.out.println("正在启动客户端.....");
            socket = new Socket("localhost",8089);
            System.out.println("客户端已经启动！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //写东西进服务端
        try {
            ServerHandler serverHandler = new ServerHandler();
            Thread t = new Thread(serverHandler);
            t.setDaemon(true); //设置为守护线程，所有普通线程执行完毕该线程才会执行完毕
            t.start();

            PrintWriter pw = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream(),"UTF-8"
                        )
                )
            ,true);
            Scanner scan = new Scanner(System.in);
            System.out.println("可以输入:");
            while (true){
               String line = scan.nextLine();
               if ("exit".equals(line)){
                   break;
               }
               pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String serverMessage;
                while ((serverMessage = br.readLine()) != null){
                    System.out.println(serverMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Client1 clinet1 = new Client1();
        clinet1.start();
    }
}
